﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WHC.Hotel.Entity;
using WHC.Hotel.BLL;

using WHC.Hotel.UI.Controls;
using WHC.OrderWater.Commons;

namespace WHC.Hotel.UI
{
    public partial class FrmRoomCheckOut : BaseForm
    {
        public RoomInfo RoomInfo = null;

        private decimal amountMoney = 0.0M;
        private decimal offerMoney = 0.0M;
        private OrderInfo orderInfo = null;
        private  List<ConsumerListInfo> consumerList = new List<ConsumerListInfo>();
        private List<ConsumerListInfo> RoomDayChargeList = new List<ConsumerListInfo>();
        private OrderInfo teamVirtualOrder = null;

        public FrmRoomCheckOut()
        {
            InitializeComponent();
        }

        private void FrmRoomCheckOut_Load(object sender, EventArgs e)
        {            
            if (RoomInfo != null)
            {
                ShowRoomTreeView();
                BindData(RoomInfo);
                CheckOutValid();
            }
        }

        /// <summary>
        /// 退房检查
        /// </summary>
        private void CheckOutValid()
        {

            if (orderInfo.IsAudit == 1)//夜审后才需要判断
            {
                if (DateTime.Now.Hour >= SystemConfig.Default.KFMoneyHalfAtHour &&
                          DateTime.Now.Hour <= SystemConfig.Default.KFMoneyAddDayAtHour)
                {
                    lbWarn.Text = "时间超过中午" + SystemConfig.Default.KFMoneyHalfAtHour + "点,请先加收半天房费再结账";
                }
                else if (DateTime.Now.Hour > SystemConfig.Default.KFMoneyAddDayAtHour)
                {
                    lbWarn.Text = "时间超过" + SystemConfig.Default.KFMoneyAddDayAtHour + "点,请先加收一天房费再结账";
                }

            }
        
        
        }
    

        private void BindData(RoomInfo info)
        {
            if (info != null)
            {
                this.groupConsumeList.Text = string.Format("{0} {1}", info.RoomNo, "消费清单");

                orderInfo = BLLFactory<Order>.Instance.GetCurrentOrder(info.RoomNo);

               
                if (orderInfo == null)
                {
                    MessageUtil.ShowWarning("不存在该订单");
                    this.Close();
                    return;
                   
                }
                if (orderInfo.CheckType == 1)
                {
                    teamVirtualOrder = BLLFactory<Order>.Instance.FindSingle(" MasterRoomNo='" + orderInfo.MasterRoomNo + "'  and   IsVirtualAccount=1 ");


                }
                else
                {
                    if (orderInfo.MasterRoomNo != orderInfo.RoomNo)
                    {
                        orderInfo = BLLFactory<Order>.Instance.GetCurrentOrder(orderInfo.MasterRoomNo);
                    }
                
                }
                amountMoney = OnShowStatus(info);
                this.lblAllMoney.Text = string.Format("消费总金额：{0:C2}", amountMoney);

                this.lblRoomNo.Text = info.RoomNo;
                this.lblRoomType.Text = info.RoomType;

                if (orderInfo != null)
                {

                    if (orderInfo.IsPartTime)
                    {

                        lbNameLiveCount.Text = "入住时长";
                        lbliveCount.Text = BLLFactory<Room>.Instance.GetRoomQuantity(orderInfo).ToString() + "（小时）";

                    }
                    else
                    {

                        lbliveCount.Text = BLLFactory<Room>.Instance.GetRoomQuantity(orderInfo).ToString() + "（天）";
                    }

                    if (orderInfo.CheckType == 1)
                    {

                        //CustomerInfo customerInfo = BLLFactory<Customer>.Instance.FindByID(orderInfo.Customer_ID);
                        //if (customerInfo == null)
                        //{
                        //    MessageUtil.ShowTips("已经不存在该客户信息");
                        //    this.Close();
                        //    return;
                        //}
                        this.lblName.Text = teamVirtualOrder.TeamName;
                        this.txtName.Text = teamVirtualOrder.TeamName;
                        this.lblCompany.Text ="";
                        this.lblCustomerType.Text = "团体客户";
                        this.lblAmount.Text = amountMoney.ToString("C2");
                        this.lblAmount.Tag = amountMoney;
                        this.lblConsume.Text = amountMoney.ToString("C2");
                        this.lblConsume.Tag = amountMoney;
                        this.lblYouhui.Text = offerMoney.ToString("C2");
                        this.lblYouhui.Tag = offerMoney;
                        this.lblDeposit.Text = teamVirtualOrder.DepositMoney.ToString("C2");
                        this.lblDeposit.Tag = teamVirtualOrder.DepositMoney;
                        this.txtAmount.Text = amountMoney.ToString("f2");
                        this.txtAmount.Tag = amountMoney;
                        this.lbArriveTime.Text = teamVirtualOrder.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
                        this.lbleaveTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        this.lbCardNum.Text = teamVirtualOrder.CreditCardNum;
                        this.lbPreGrantNum.Text = teamVirtualOrder.PreGrantNum;


                        this.txtPay.Text = "0.00";
                        txtPay_TextChanged(null, null);
                        this.txtPay.Focus();
                        this.lblCheckOutNo.Text = teamVirtualOrder.BillNumber;
                        lblRoomType.Text = "团体结账";
                        lblRoomNo.Text = "团体结账";
                    }
                    else
                    {


                        CustomerInfo customerInfo = BLLFactory<Customer>.Instance.FindByID(orderInfo.Customer_ID);
                        if (customerInfo == null)
                        {
                            MessageUtil.ShowTips("已经不存在该客户信息");
                            this.Close();
                            return;
                        }
                        this.lblName.Text = orderInfo.CustomerName;
                        this.txtName.Text = orderInfo.CustomerName;
                        this.lblCompany.Text = customerInfo.CompanyName;
                        this.lblCustomerType.Text = customerInfo.CustomerType;
                        this.lblAmount.Text = amountMoney.ToString("C2");
                        this.lblAmount.Tag = amountMoney;
                        this.lblConsume.Text = amountMoney.ToString("C2");
                        this.lblConsume.Tag = amountMoney;
                        this.lblYouhui.Text = offerMoney.ToString("C2");
                        this.lblYouhui.Tag = offerMoney;
                        this.lblDeposit.Text = orderInfo.DepositMoney.ToString("C2");
                        this.lblDeposit.Tag = orderInfo.DepositMoney;
                        this.txtAmount.Text = amountMoney.ToString("f2");
                        this.txtAmount.Tag = amountMoney;
                        this.lbArriveTime.Text = orderInfo.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
                        this.lbleaveTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        this.lbCardNum.Text = orderInfo.CreditCardNum;
                        this.lbPreGrantNum.Text = orderInfo.PreGrantNum;


                        this.txtPay.Text = "0.00";
                        txtPay_TextChanged(null, null);
                        this.txtPay.Focus();

                        if (!string.IsNullOrEmpty(orderInfo.OrderNo))
                        {
                            this.lblCheckHandNo.Text = orderInfo.BillNumber;
                        }
                        else
                        {
                            this.lblCheckHandNo.Text = "无";
                        }

                    }

                    //this.lblCheckOutNo.Text = BLLFactory<RoomBill>.Instance.GetRoomBillNumber();//账单编号
                   
                }
            }
        }

        private void ShowRoomTreeView()
        {
            #region 项目类型信息明细类别

            this.treeView1.Nodes.Clear();
            this.treeView1.BeginUpdate();

            List<RoomTypeInfo> typeList = BLLFactory<RoomType>.Instance.GetAll();
            foreach (RoomTypeInfo typeInfo in typeList)
            {
                string nodeName = string.Format("{0}  {1}", typeInfo.Name, typeInfo.DayPrice);
                TreeNode typeNode = new TreeNode(nodeName, 0, 0);
                this.treeView1.Nodes.Add(typeNode);
                //typeNode.Tag = info;

                List<RoomInfo> roomList = BLLFactory<Room>.Instance.FindRooms(typeInfo.Name, RoomStatus.住净房.ToString());
                foreach (RoomInfo roomInfo in roomList)
                {
                    TreeNode subNode = new TreeNode(roomInfo.RoomNo, 1, 1);
                    subNode.Tag = roomInfo;
                    typeNode.Nodes.Add(subNode);
                }
            }
            this.treeView1.EndUpdate();
            this.treeView1.ExpandAll();

            #endregion
        }
        
        private decimal OnShowStatus(RoomInfo roomInfo)
        {
            decimal allMoney = 0.0M;

            #region 更新消费记录

            consumerList.Clear();
            if (roomInfo != null)
            {

                if (orderInfo.CheckType == 0)//散客
                {
                    //先判断是否夜审过
                    if (orderInfo.IsAudit == 1)
                    {

                        consumerList = BLLFactory<Room>.Instance.GetGoodsConsumption(roomInfo.RoomNo);

                    }
                    else //表示当天就退房
                    {

                        RoomDayChargeList = BLLFactory<Room>.Instance.GetRoomConsumption(roomInfo.RoomNo);//日房费
                        consumerList.AddRange(RoomDayChargeList);
                        consumerList.AddRange(BLLFactory<Room>.Instance.GetGoodsConsumption(roomInfo.RoomNo));

                    }

                }
                else //团体
                {

                    if (teamVirtualOrder != null)
                    {

                        consumerList = BLLFactory<ConsumerList>.Instance.Find("   Account='" + teamVirtualOrder.BillNumber + "'  ");
  
                    
                    }
                    
                
                }

               
                this.lvwDetail.Items.Clear();
                int i = 1;
                offerMoney = 0.0M;
                foreach (ConsumerListInfo info in consumerList)
                {
                    ListViewItem item = new ListViewItem(info.RoomNo);
                    item.SubItems.Add(info.ItemName);
                    item.SubItems.Add(info.Price.ToString("C2"));
                    item.SubItems.Add(info.Discount.ToString());
                    item.SubItems.Add(info.DiscountPrice.ToString("C2"));
                    offerMoney += info.Price - info.DiscountPrice;//优惠金额
                    item.SubItems.Add((info.Price - info.DiscountPrice).ToString("C2"));
                    item.SubItems.Add(info.Quantity.ToString());
                    item.SubItems.Add(info.Amount.ToString("C2"));
                    item.SubItems.Add(info.BeginTime.ToString());
                    item.SubItems.Add(info.Creator);
                    if (info.IsCheckout == 0)
                    {
                        item.SubItems.Add("未结账");

                    }
                    else
                    {
                        item.SubItems.Add("已结账");
                    
                    }
                    item.Tag = info;
                    if (info.Quantity < 0)
                    {
                        item.ForeColor = Color.Red;
                    }

                    this.lvwDetail.Items.Add(item);
                    if (info.IsCheckout == 0)
                    {
                        allMoney += info.Amount;

                    }
                    i++;
                }
            }
            #endregion

            return allMoney;
        }
        
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode selectedNode = e.Node;
            if (selectedNode.Tag != null)
            {
                RoomInfo info = selectedNode.Tag as RoomInfo;
                if (info != null)
                {
                    RoomInfo = info;//重新更新变量，方便结算
                    BindData(info);
                }
            }
        }

        private void txtPay_TextChanged(object sender, EventArgs e)
        {
            string payInput = "0";
            if (txtPay.Text.Trim('-').Length > 0)
            {
                payInput = txtPay.Text;
            }

            decimal payMoney = Convert.ToDecimal(payInput);
            decimal amount = Convert.ToDecimal(this.txtAmount.Text);
            decimal deposit = GetDeposit();
            this.lblChange.Text = (payMoney + deposit - amount).ToString("f2");
        }

        private string GetPayType()
        {
            string result = "已结账";
            if (this.chkSign.Checked)
            {
                result = chkSign.Text;
            }
            else if (this.chkHoldup.Checked)
            {
                result = chkHoldup.Text;
            }
            else if (this.chkFree.Checked)
            {
                result = chkFree.Text;
            }
            else if (this.chkBack.Checked)
            {
                result = chkBack.Text;
            }

            return result;
        }

        private decimal GetDeposit()
        {
            decimal deposit = Convert.ToDecimal(this.lblDeposit.Tag);
            if (this.chkSign.Checked || this.chkHoldup.Checked || this.chkFree.Checked)
            {
                if (this.chkDeposit.Checked)
                {
                    deposit = 0M;//退押金
                }
            }
            return deposit;
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageUtil.ShowYesNoAndTips("您是否确定结账") != DialogResult.Yes)
                    return;

                #region 构造账单信息

                if (this.chkSign.Checked && this.txtName.Text.Trim() == "")
                {
                    MessageUtil.ShowTips("签单需要指定客户，请选择客户");
                    this.txtName.Focus();
                    return;
                }

                decimal amount = Convert.ToDecimal(this.txtAmount.Text);
                decimal payMoney = Convert.ToDecimal(this.txtPay.Text);
                decimal deposit = GetDeposit();
                bool isOtherCheckOut = this.chkBack.Checked || this.chkFree.Checked || this.chkHoldup.Checked || this.chkSign.Checked;
                if ((payMoney + deposit) < amount && !isOtherCheckOut)
                {
                    MessageUtil.ShowTips("付款金额不足，不能进行结账");
                    this.txtPay.Focus();
                    return;
                }

                RoomBillInfo billInfo = new RoomBillInfo();
                billInfo.BillNumber = this.lblCheckOutNo.Text;
                billInfo.Cash = amount;
                billInfo.CheckStatus = GetPayType();//"已结账";
                billInfo.Consumption = Convert.ToDecimal(this.lblConsume.Tag);
                billInfo.CreateDate = DateTime.Now;
                billInfo.Creator = Portal.gc.LoginInfo.FullName;
                billInfo.CustomerName = this.chkSign.Checked ? this.txtName.Text :  this.lblName.Text;
                billInfo.Deposit = GetDeposit();
                billInfo.InHotelDate = orderInfo.CreateDate;//入店时间
                billInfo.Invoice = this.chkFP.Checked;
                billInfo.KeepChange = Convert.ToDecimal(this.lblChange.Text);
                billInfo.Note = this.txtNote.Text;
                billInfo.OfferMoney = Convert.ToDecimal(this.lblYouhui.Tag);
                billInfo.PayMoney = Convert.ToDecimal(this.txtAmount.Text);
                billInfo.PayType = "现金";
                billInfo.RoomNo = this.lblRoomNo.Text; 

                #endregion

                if (billInfo.CheckStatus == CheckStatus.退单.ToString())
                {
                    //退单的时候，把消费的商品退回去（增加退货记录）
                    //同时还原库存
                    //List<ConsumerListInfo> consumerList = BLLFactory<Room>.Instance.GetGoodsConsumption(RoomInfo.RoomNo);
                    //foreach (ConsumerListInfo consumerInfo in consumerList)
                    //{
                    //    int originalQuantity = Convert.ToInt32(consumerInfo.Quantity);
                    //    consumerInfo.Amount = -consumerInfo.Amount;
                    //    consumerInfo.Quantity = -consumerInfo.Quantity;
                    //    bool tempFlag = BLLFactory<ConsumerList>.Instance.Insert(consumerInfo);
                    //    if (tempFlag)
                    //    {
                    //        BLLFactory<Goods>.Instance.AddStockQuantiy(consumerInfo.ItemNo, consumerInfo.ItemName, originalQuantity);
                    //    }
                    //}
                }
                else
                {
                    //结帐前，需要写入计算好的房间消费清单到数据库中
                    //（因为结账前的房间费用都是动态计算的，没有写入数据库中）
                   // List<ConsumerListInfo> consumerList = BLLFactory<Room>.Instance.GetRoomConsumption(RoomInfo.RoomNo);
                    foreach (ConsumerListInfo consumerInfo in RoomDayChargeList)
                    {
                        BLLFactory<ConsumerList>.Instance.Insert(consumerInfo);
                    }
                }

                //获取不同的房间列表，方便统一设置状态
                List<string> roomList = new List<string>();
                foreach (ListViewItem item in lvwDetail.Items)
                {
                    string roomNo = item.SubItems[0].Text;
                    if (!roomList.Contains(roomNo))
                    {
                        roomList.Add(roomNo);
                    }
                }

                bool success = BLLFactory<RoomBill>.Instance.CheckOutRoom(billInfo, orderInfo, roomList);
                //更改消费明细结账状态
                if (orderInfo.CheckType == 1)
                {

                    BLLFactory<ConsumerList>.Instance.UpdateConsumeStatus(teamVirtualOrder.BillNumber, 1, "");
                }
                else
                {

                    BLLFactory<ConsumerList>.Instance.UpdateConsumeStatus(orderInfo.BillNumber, 1, "");
                
                }
               
                if (!success)
                {
                    MessageUtil.ShowWarning("房间结账失败");
                    return;
                }

                #region 增加收银明细
                string note = string.Format("[结账时{0}退押金]", this.chkDeposit.Checked ? "已" : "未");
                decimal money = (amountMoney - orderInfo.DepositMoney);//默认该次收取金额=实收-押金
                if (this.chkDeposit.Checked)
                {
                    money = -1 * Convert.ToDecimal(this.lblDeposit.Tag);//退押金
                }

                if (this.chkFree.Checked)
                {
                    note += this.chkFree.Text;
                }
                else if (this.chkHoldup.Checked)
                {
                    note += this.chkHoldup.Text;
                }
                else if (this.chkBack.Checked)
                {
                    note += this.chkBack.Text;
                }
                else if (this.chkSign.Checked)
                {
                    note += this.chkSign.Text;
                }
                else
                {
                    note += "已结账";
                }
                note += string.Format(" 结账单号:{0} {1}", billInfo.BillNumber, this.txtNote.Text);
                AddMoneyDetail(money, billInfo.PayType, note); 
                #endregion

                this.DialogResult = DialogResult.OK;//成功
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                MessageUtil.ShowError(ex.Message);
            }
        }

        /// <summary>
        /// 增加收银记录
        /// </summary>
        /// <returns></returns>
        private void AddMoneyDetail(decimal payMoney, string payType, string note)
        {
            if (payMoney != 0M)
            {
                MoneyDetailInfo info = new MoneyDetailInfo();
                info.Cash = payMoney;
                info.CashierType = "结账收银";
                info.Creator = Portal.gc.LoginInfo.FullName;
                info.PayDate = DateTime.Now;
                info.Customer_ID = orderInfo.Customer_ID;
                info.CustomerName = orderInfo.CustomerName;
                info.RoomNo = orderInfo.RoomNo;
                info.PayType = payType;
                info.Note = note;

                BLLFactory<MoneyDetail>.Instance.Insert(info);
            }
        }

        private void btnUnitedCheck_Click(object sender, EventArgs e)
        {
            FrmUnitedCheckOut dlg = new FrmUnitedCheckOut();
            dlg.orderInfo = orderInfo;
            dlg.lblAmount.Text = Convert.ToDecimal(this.lblAmount.Tag).ToString("f2");
            dlg.lblDeposit.Text = orderInfo.DepositMoney.ToString("f2");

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    #region 构造账单信息

                    decimal amount = Convert.ToDecimal(this.txtAmount.Text);
                    decimal payMoney = Convert.ToDecimal(this.txtPay.Text);

                    RoomBillInfo billInfo = new RoomBillInfo();
                    billInfo.BillNumber = this.lblCheckOutNo.Text;
                    //支付信息
                    billInfo.Cash = Convert.ToDecimal(dlg.txtCashPay.Text);
                    billInfo.Card = Convert.ToDecimal(dlg.txtCard.Text);
                    billInfo.CardNumber = dlg.txtCardNumber.Text;
                    billInfo.NationalCredit = Convert.ToDecimal(dlg.txtNationalCredit.Text);
                    billInfo.CreditCardNumber = dlg.txtNationalCreditCard.Text;
                    billInfo.InterCredit = Convert.ToDecimal(dlg.txtInterCredit.Text);
                    billInfo.InterCreditCardNumber = dlg.txtInterCreditCard.Text;
                    billInfo.DaijinTicket = Convert.ToDecimal(dlg.txtDaijinTicket.Text);
                    billInfo.KeepChange = Convert.ToDecimal(dlg.lblChange.Text);
                    billInfo.Deposit = Convert.ToDecimal(dlg.lblDeposit.Text);
                    billInfo.Note = dlg.txtNote.Text;

                    billInfo.CheckStatus = "已结账";
                    billInfo.Consumption = Convert.ToDecimal(this.lblConsume.Tag);
                    billInfo.CreateDate = DateTime.Now;
                    billInfo.Creator = Portal.gc.LoginInfo.FullName;
                    billInfo.CustomerName = this.lblName.Text;
                    billInfo.InHotelDate = orderInfo.CreateDate;//入店时间
                    billInfo.Invoice = this.chkFP.Checked;
                    billInfo.OfferMoney = Convert.ToDecimal(this.lblYouhui.Tag);
                    billInfo.PayMoney = Convert.ToDecimal(this.txtAmount.Text);
                    billInfo.PayType = "联合";
                    billInfo.RoomNo = this.lblRoomNo.Text;

                    #endregion

                    //获取不同的房间列表，方便统一设置状态
                    List<string> roomList = new List<string>();
                    foreach (ListViewItem item in lvwDetail.Items)
                    {
                        string roomNo = item.SubItems[0].Text;
                        if (!roomList.Contains(roomNo))
                        {
                            roomList.Add(roomNo);
                        }
                    }
                    bool success = BLLFactory<RoomBill>.Instance.CheckOutRoom(billInfo, orderInfo, roomList);

                    //结帐前，需要写入计算好的房间消费清单到数据库中
                    //（因为结账前的房间费用都是动态计算的，没有写入数据库中）
                    // List<ConsumerListInfo> consumerList = BLLFactory<Room>.Instance.GetRoomConsumption(RoomInfo.RoomNo);
                    foreach (ConsumerListInfo consumerInfo in RoomDayChargeList)
                    {
                        BLLFactory<ConsumerList>.Instance.Insert(consumerInfo);
                    }
                    //更改消费明细结账状态
                    BLLFactory<ConsumerList>.Instance.UpdateConsumeStatus(orderInfo.BillNumber, 1, "");
                    if (!success)
                    {
                        MessageUtil.ShowWarning("房间结账失败");
                        return;
                    }

                   
                   
               

                    #region 添加收银明细
                    string note = string.Format("[联合支付时退押金]结账单号:{0}", billInfo.BillNumber);
                    AddMoneyDetail(-orderInfo.DepositMoney, "现金", note);

                    MoneyDetailInfo info = new MoneyDetailInfo();
                    info.Cash = billInfo.Cash;
                    info.Card = billInfo.Card;
                    info.DaijinTicket = billInfo.DaijinTicket;
                    info.InterCredit = billInfo.InterCredit;
                    info.NationalCredit = billInfo.NationalCredit;
                    info.CashierType = "结账收银";
                    info.Creator = Portal.gc.LoginInfo.FullName;
                    info.PayDate = DateTime.Now;
                    info.Customer_ID = orderInfo.Customer_ID;
                    info.CustomerName = orderInfo.CustomerName;
                    info.RoomNo = orderInfo.RoomNo;
                    info.PayType = billInfo.PayType;
                    info.Note = dlg.txtNote.Text;
                    BLLFactory<MoneyDetail>.Instance.Insert(info); 
                    #endregion

                    this.DialogResult = DialogResult.OK;//成功
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
        }

        private void btnPrintDetail_Click(object sender, EventArgs e)
        {
            FrmPrintOptions dlg = new FrmPrintOptions();
            dlg.txtTitle.Text = string.Format("{0}\r\n酒店客房({1})结账清单      账单号：{2}\r\n",
                Portal.gc.gAppUnit, RoomInfo.RoomNo, this.lblCheckOutNo.Text);
            decimal amount = Convert.ToDecimal(this.txtAmount.Text);//实收
            dlg.txtBottom.Text = string.Format("{0}           实收：{1}(大写：{2})      现金：{3}      找零{4}",
                lblAllMoney.Text, amount.ToString("C2"), RMBUtil.CmycurD(amount), Convert.ToDecimal(this.txtPay.Text).ToString("C2"),
                Convert.ToDecimal(this.lblChange.Text).ToString("C2"));
            dlg.txtBottom.Text += string.Format("\r\n签单单位：                          签单人：\t\r\n");
            dlg.listView = lvwDetail;
            dlg.ShowDialog();
        }

        private void ResetStatus()
        {
            this.chkDeposit.Checked = false;

            decimal payMoney = 0.00M;
            this.txtPay.Text = payMoney.ToString("f2");
            this.txtPay.Focus();

            decimal amount = Convert.ToDecimal(this.lblAmount.Tag);
            decimal deposit = Convert.ToDecimal(this.lblDeposit.Tag);
            this.txtAmount.Text = (amount).ToString("f2");
            this.txtNote.Text = "";

            txtPay_TextChanged(null, null);
        }

        private void chkSign_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSign.Checked)
            {
                this.chkBack.Checked = false;
                this.chkFree.Checked = false;
                this.chkHoldup.Checked = false;
                this.chkDeposit.Checked = false;

                decimal amount = Convert.ToDecimal(this.txtAmount.Text);
                this.txtPay.Text = amount.ToString("f2");
                txtPay_TextChanged(null, null);
                this.txtNote.Text = string.Format("{0}签单金额:{1}",
                    Portal.gc.LoginInfo.FullName, this.txtPay.Text);
            }
            else
            {
                ResetStatus();
            }
        }

        private void chkHoldup_CheckedChanged(object sender, EventArgs e)
        {
            if (chkHoldup.Checked)
            {
                this.chkBack.Checked = false;
                this.chkFree.Checked = false;
                this.chkSign.Checked = false;
                this.chkDeposit.Checked = true;

                this.txtPay.Text = "0.00";
                this.txtAmount.Text = "0.00";
                this.txtNote.Text = chkHoldup.Text;
                txtPay_TextChanged(null, null);
            }
            else
            {
                ResetStatus();
            }
        }

        private void chkFree_CheckedChanged(object sender, EventArgs e)
        {
            if (chkFree.Checked)
            {
                this.chkBack.Checked = false;
                this.chkSign.Checked = false;
                this.chkHoldup.Checked = false;
                this.chkDeposit.Checked = true;

                this.txtPay.Text = "0.00";
                this.txtAmount.Text = "0.00";
                this.lblChange.Text = "0.0";
                txtPay_TextChanged(null, null);
                this.txtNote.Text = chkFree.Text;
            }
            else
            {
                ResetStatus();
            }
        }

        private void chkBack_CheckedChanged(object sender, EventArgs e)
        {
            if (chkBack.Checked)
            {
                this.chkSign.Checked = false;
                this.chkFree.Checked = false;
                this.chkHoldup.Checked = false;
                this.chkDeposit.Checked = true;

                this.txtPay.Text = "0.00";
                this.txtAmount.Text = "0.00";
                txtPay_TextChanged(null, null);
                this.txtNote.Text = chkBack.Text;
            }
            else
            {
                ResetStatus();
            }
        }

        private void btnPosPrint_Click(object sender, EventArgs e)
        {
            if (this.lvwDetail.Items.Count == 0)
            {
                MessageUtil.ShowTips("没有消费记录");
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}\r\n\r\n", Portal.gc.gAppUnit);
            sb.AppendFormat("客房消费\r\n");
            sb.AppendFormat("结账单号：{0}\r\n", this.lblCheckOutNo.Text);
            sb.AppendFormat("客户姓名：{0}\r\n", this.txtName.Text);
            sb.AppendFormat("结账客房：{0}\r\n", RoomInfo.RoomNo);
            sb.AppendFormat("打印时间：{0}\r\n\r\n", DateTime.Now);

            sb.AppendFormat("项目     单价  数量  金额\r\n");
            for (int i = 0; i < lvwDetail.Items.Count; i++)
            {
                ListViewItem item = lvwDetail.Items[i];
                string itemName = item.SubItems[1].Text;
                if (itemName.Contains("买断消费"))
                {
                    itemName = "买断消费";
                }
                sb.AppendFormat("{0}", itemName);
                sb.AppendFormat(" {0}", item.SubItems[2].Text);
                sb.AppendFormat(" {0}", item.SubItems[6].Text);
                sb.AppendFormat(" {0}\r\n", item.SubItems[7].Text);
            }
            sb.AppendFormat("\r\n\r");
            sb.AppendFormat("总 金 额：{0}\r\n", Convert.ToDecimal(this.lblConsume.Tag).ToString("C2"));
            sb.AppendFormat("实收金额：{0}\r\n", Convert.ToDecimal(this.txtAmount.Text).ToString("C2"));
            sb.AppendFormat("实收大写：{0}\r\n", RMBUtil.CmycurD(this.txtAmount.Text));
            sb.AppendFormat("现    金：{0}\r\n", Convert.ToDecimal(this.txtPay.Text).ToString("C2"));
            sb.AppendFormat("找    零：{0}\r\n", Convert.ToDecimal(this.lblChange.Text).ToString("C2"));
            sb.AppendFormat("\r\n\r");

            Portal.gc.PosPrint(sb.ToString());
        }

        private void menu_Discount_Click(object sender, EventArgs e)
        {
            FrmDiscount dlg = new FrmDiscount();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                foreach (ListViewItem item in this.lvwDetail.SelectedItems)
                {
                    ConsumerListInfo info = item.Tag as ConsumerListInfo;
                    if (info != null)
                    {
                        //赠送的不再参与打折
                        if (info.ItemName.Contains("(赠)"))
                        {
                            continue;
                        }

                        double rate = Convert.ToDouble(dlg.txtDiscountRate.Text);
                        info.Discount = rate;
                        info.DiscountPrice = info.Price * Convert.ToDecimal(rate);
                        info.Amount = info.DiscountPrice * Convert.ToDecimal(info.Quantity);

                        BLLFactory<ConsumerList>.Instance.Update(info, info.ID.ToString());
                        if (info.ItemName == "房间费" && info.ID == 0)
                        {
                            RoomTempDiscountInfo tempInfo = BLLFactory<RoomTempDiscount>.Instance.GetDiscount("客房", info.Order_ID, info.RoomNo);
                            if (tempInfo != null)
                            {
                                tempInfo.DiscountRate = rate;
                                BLLFactory<RoomTempDiscount>.Instance.Update(tempInfo, tempInfo.ID.ToString());
                            }
                            else
                            {
                                tempInfo = new RoomTempDiscountInfo();
                                tempInfo.DiscountRate = rate;
                                tempInfo.Order_ID = info.Order_ID;
                                tempInfo.OrderType = "客房";
                                tempInfo.RoomNo = info.RoomNo;
                                tempInfo.CreateDate = DateTime.Now;
                                BLLFactory<RoomTempDiscount>.Instance.Insert(tempInfo);
                            }
                        }
                    }
                }

                BindData(RoomInfo);
            }
        }

        private void lvwDetail_DoubleClick(object sender, EventArgs e)
        {
            menu_Discount_Click(null, null);
        }

        private void txtAmount_TextChanged(object sender, EventArgs e)
        {
            txtPay_TextChanged(null, null);
        }

        private void ChangeCustomer(string customerID)
        {
            if (!string.IsNullOrEmpty(customerID))
            {
                CustomerInfo info = BLLFactory<Customer>.Instance.FindByID(customerID);
                if (info != null)
                {
                    this.txtName.Text = info.Name;
                }
            }
        }

        private void btnNameSearch_Click(object sender, EventArgs e)
        {
            FrmCustomerSearch dlg = new FrmCustomerSearch();
            dlg.txtName.Text = this.txtName.Text;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.SelectedID))
                {
                    ChangeCustomer(dlg.SelectedID);
                }
            }
        }

    }
}
